using System;
using System.Globalization;
using System.IO.Compression;
using System.Threading;
using System.Web;
using System.Web.UI;

namespace ScrewTurn.Wiki 
{

	public class BasePage : Page {

		public BasePage()
        {
		}

		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);
			// Request might not be initialized -> use HttpContext
			string ua = HttpContext.Current.Request.UserAgent != null ? HttpContext.Current.Request.UserAgent.ToLowerInvariant() : "";
			if(Settings.EnableHttpCompression && !ua.Contains("konqueror") && !ua.Contains("safari")) {
				if(Request.Headers["Accept-encoding"] != null && Request.Headers["Accept-encoding"].Contains("gzip")) {
					Response.Filter = new GZipStream(Response.Filter, CompressionMode.Compress, true);
					Response.AppendHeader("Content-encoding", "gzip");
					Response.AppendHeader("Vary", "Content-encoding");
				}
				else if(Request.Headers["Accept-encoding"] != null && Request.Headers["Accept-encoding"].Contains("deflate")) {
					Response.Filter = new DeflateStream(Response.Filter, CompressionMode.Compress, true);
					Response.AppendHeader("Content-encoding", "deflate");
					Response.AppendHeader("Vary", "Content-encoding");
				}
			}
		}

		protected override void InitializeCulture() {
			if(Request.Cookies[Settings.CultureCookieName] != null) {
				HttpCookie cookie = Request.Cookies[Settings.CultureCookieName];
				string culture = cookie["C"];
				Thread.CurrentThread.CurrentCulture = new CultureInfo(culture);
				Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
			}
			else {
				try {
					if(Settings.DefaultLanguage.Equals("-")) {
						Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
						Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
					}
					else {
						Thread.CurrentThread.CurrentCulture = new CultureInfo(Settings.DefaultLanguage);
						Thread.CurrentThread.CurrentUICulture = new CultureInfo(Settings.DefaultLanguage);
					}
				}
				catch {
					Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
					Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
				}
			}
		}

	}

}
